package com.milling.web.utils;

import com.alibaba.fastjson2.JSONObject;
import com.milling.business.BusinessConstants;
import com.milling.business.GlobalVariable;
import com.milling.business.domain.WmsSortingInstockHistory;
import com.milling.business.service.IWmsNeedleSorttingService;
import com.milling.business.service.IWmsSortingInstockHistoryService;
import com.milling.business.service.SuspendTaskManager;
import com.milling.common.core.redis.RedisCache;
import com.milling.common.utils.SocketUtils;
import com.milling.common.utils.StringUtils;
import com.milling.common.utils.http.WmsApiUtils;
import com.milling.common.utils.modbus.ModbusServiceFactory;
import com.milling.common.utils.modbus.ModbusTcpService;
import com.milling.common.utils.scanner.SocketListener;
import com.milling.common.utils.uuid.UUID;
import com.milling.web.SpringContextHolder;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

@Configuration
@ConditionalOnProperty(
        name = "mac.type",
        havingValue = "2",
        matchIfMissing = false // 当配置缺失时不加载
)
@Component
public class InstockScanner implements SocketListener.MessageCallback {
    private static final Logger logger = LoggerFactory.getLogger(InstockScanner.class);

    @Value("${sorting.scanner.instockip}")
    private String instockIp;

    @Value("${sorting.scanner.port}")
    private int instockPort;

    @Autowired
    private SuspendTaskManager suspendTaskManager;

    private SocketUtils socketUtils; // 声明为成员变量

    // 从参数中读取IP、端口、slaveId和连接池大小
    @Value("${modbus.sorting.host:192.168.237.178}")
    private String host; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.port:502}")
    private int port; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.poolSize:5}")
    private int poolSize; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.slaveId:1}")
    private int slaveId;

    @Autowired
    private IWmsSortingInstockHistoryService wmsSortingInstockHistoryService;

    // 获取Modbus服务实例
    private ModbusTcpService modbusTcpService;
    @Autowired
    private RedisCache redisCache;

    @PostConstruct
    public void init() {
        // 初始化 Modbus 服务
        modbusTcpService = ModbusServiceFactory.getModbusService(host, port, poolSize);
        logger.info("InstockScanner Modbus服务初始化完成 - {}:{}", host, port);

        // 初始化扫码器连接
        // 注意：SortingScanner 使用按需连接方式，不需要持久连接
    }

    @Autowired
    public InstockScanner(@Value("${sorting.scanner.instockip}") String instockIp, @Value("${sorting.scanner.port}") int instockPort) {
        this.instockIp = instockIp;
        this.instockPort = instockPort;
        this.socketUtils = new SocketUtils(instockIp, instockPort); // 初始化
    }

    @Override
    public void onMessageReceived(String message) {
        // 创建连接池

//        logger.error("[分拣机扫码结果] " + message);
//        if("NoRead".equals(message)){
        if(message.contains("NoRead")){
            // 修复无限重试问题：添加扫码次数限制
            if(GlobalVariable.maxScanTimes <= 5) {
                GlobalVariable.maxScanTimes = GlobalVariable.maxScanTimes + 1;
                try {
                    //扫码 - 使用try-with-resources确保资源正确释放
                    try (SocketUtils tempSocketUtils = new SocketUtils(instockIp, instockPort)) {
                        tempSocketUtils.sendMessage("start");
                        Thread.sleep(50);
                    }
                } catch (Exception e) {
                    logger.error("[PLC]入库扫码器扫码失败", e);
                }
            } else {
                // 超过最大重试次数，重置计数器并记录错误
                synchronized(this) {
                    GlobalVariable.maxScanTimes = 0;
                }
                logger.error("入库扫码器扫码失败次数超过限制，已重置扫码计数器");
                // 可以在这里添加报警逻辑
            }
        } else {
            // 扫码成功，重置扫码次数
            synchronized(this) {
                GlobalVariable.maxScanTimes = 0;
            }
            logger.info("入库扫码结果 " + message);

            redisCache.setCacheObject("QRCODE-VALUE", message);

        }
    }

    @Override
    public void onConnectionClosed() {
        System.out.println("[INFO] SortingScanner Connection closed by server");
    }

    @Override
    public void onError(String errorMsg) {
        System.err.println("[ERROR] " + errorMsg);
    }

}
